package com.qf.pay.controller;

import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayUtil;
import com.qf.pay.config.WXConfig;
import com.qf.pay.service.IpayService;
import com.qf.pck.entity.Package;
import com.qf.pck.entity.PackageOrder;
import com.qf.pck.mapper.PackageMapper;
import com.qf.pck.mapper.PackageOrderMapper;
import com.qf.vo.R;
import com.qf.websocket.WebSocketEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@CrossOrigin
@Slf4j
public class PayController {

    @Autowired
    private IpayService ipayService;

    @Autowired
    private PackageOrderMapper packageOrderMapper;


    @Autowired
    private PackageMapper packageMapper;


    @GetMapping("/getCodeUrl/{orderId}")
    public R<String> getCodeUrl(@PathVariable String orderId){
        return ipayService.getPayUrl(orderId);
    }


    @RequestMapping("/pay-result-notify")
    public String notify(HttpServletRequest request){
        try {


            log.info("支付成功,异步通知......");

            //1：接受微信的通知参数
            ServletInputStream inputStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer)) != -1){
                outSteam.write(buffer,0,len);
            }
            outSteam.close();
            inputStream.close();
            String resultXML = new String(outSteam.toByteArray(),"utf-8");
            log.info("支付成功,异步通知,通知参数{}",resultXML);
            //2：验签
            boolean signatureValid = WXPayUtil.isSignatureValid(resultXML, new WXConfig().getKey());
            if(signatureValid){//合法通知
                Map<String, String> wxNotifyData = WXPayUtil.xmlToMap(resultXML);
                String out_trade_no = wxNotifyData.get("out_trade_no");
                String total_fee = wxNotifyData.get("total_fee");

                //3:比较订单金额是否与商户侧的订单金额一致
                PackageOrder order = packageOrderMapper.selectById(out_trade_no);
                //if(total_fee.equals(order.getMoney()*100+"") ){//金额一致
                if(true){
                    //4:修改商户侧的订单状态为已支付
                    order.setPayStatus(1);
                    order.setPayno(out_trade_no);
                    order.setPayTime(new Date());

                    //修改套餐的有效时间
                    order.setStartTime(new Date());
                    //获取套餐
                    Package pck = packageMapper.selectById(order.getPackageId());
                    if("月".equals(pck.getTimeunit())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MONTH,pck.getTimenum());
                        order.setEndTime(calendar.getTime());
                    }

                    if("年".equals(pck.getTimeunit())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.YEAR,pck.getTimenum());
                        order.setEndTime(calendar.getTime());
                    }

                    if("季度".equals(pck.getTimeunit())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MONTH,pck.getTimenum()*3);
                        order.setEndTime(calendar.getTime());
                    }

                    packageOrderMapper.updateById(order);

                    //响应微信
                    Map resMap = new HashMap();
                    resMap.put("return_code","SUCCESS");
                    resMap.put("return_msg","fail");

                    log.info("支付成功,异步通知,业务处理成功");

                    //通过websocket 告诉客户端，支付成功
                    WebSocketEndpoint.sessions.get(out_trade_no)
                            .getBasicRemote().sendText("paysuccess");





                    try {
                        return WXPayUtil.mapToXml(resMap);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                        return  "";
                    }



                }else{//金额不一致
                    //响应微信
                    Map resMap = new HashMap();
                    resMap.put("return_code","FAIL");
                    resMap.put("return_msg","金额不一致");

                    try {
                        return WXPayUtil.mapToXml(resMap);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                        return  "";
                    }
                }




            }else{//非法通知

                    //响应微信
                    Map resMap = new HashMap();
                    resMap.put("return_code","FAIL");
                    resMap.put("return_msg","非法通知");

                    try {
                        return WXPayUtil.mapToXml(resMap);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                        return  "";
                    }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        //响应微信
        Map resMap = new HashMap();
        resMap.put("return_code","FAIL");
        resMap.put("return_msg","非法通知");

        try {
            return WXPayUtil.mapToXml(resMap);
        } catch (Exception exception) {
            exception.printStackTrace();
            return  "";
        }

    }


}
